<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" class="dataForm">
      <div class="area-header">
        <span class="area-header-sign" />
        <span class="area-header-title">{{ $t('名称设置') }}</span>
      </div>
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('视图名称')" prop="name" style="margin-bottom: 20px !important;">
            <el-input v-model="form.name" :placeholder="$t('视图名称')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-sign" />
        <span class="area-header-title">{{ $t('筛选范围') }}</span>
      </div>
      <div class="rangeForm">
        <ul class="rangeBody">
          <li v-for="(item,index) in form.searchMainGroupList" :key="index">
            <div v-if="item.searchMainConditionsList && item.searchMainConditionsList.length > 0" class="head">
              <div class="select">
                {{ $t('组内关系') }}：
                <el-select v-model="item.relation" :placeholder="$t('请选择')">
                  <el-option v-for="item in item.relationList" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
              </div>
              <el-button icon="el-icon-delete" type="text" @click="delFiltrate(index)" />
            </div>
            <div v-if="item.searchMainConditionsList && item.searchMainConditionsList.length > 0" class="content">
              <div class="rangeItem">
                <div v-for="(Default,ind) in item.searchMainConditionsList" :key="ind">
                  <span class="rangeIndex">{{ ind + 1 }}</span>
                  <!-- 动态选择select -->
                  <el-select v-model="Default.fieldId" filterable :placeholder="$t('请选择')" clearable @change="detailsChange(index, ind, $event)">
                    <el-option v-for="field in dealdetailsList" :key="field.name" :label="$t(field.remark)" :value="field.name" />
                  </el-select>
                  <!-- 查询条件--- -->
                  <conditions v-model="Default.conditions" :type="Default.type" />
                  <searchMain v-model="Default.fieldValue" :type="Default.type" :condition="Default.conditions" :choose-list="Default.chooseList" />
                  <el-button icon="el-icon-plus" type="info" size="mini" circle class="smallC" @click="addRange(item,index)" />
                  <el-button icon="el-icon-minus" type="info" size="mini" class="smallC" :disabled="disabledButton" circle @click="delRange(item,index)" />
                </div>
              </div>
            </div>
          </li>

        </ul>
        <div class="addBtn">
          <el-button icon="el-icon-plus" type="text" @click="addFiltrate()">{{ $t('添加筛选条件') }}</el-button>
        </div>
      </div>
      <div class="area-header">
        <span class="area-header-sign" />
        <span class="area-header-title">{{ $t('颜色设置') }}</span>
      </div>
      <el-color-picker
        v-model="form.color"
        show-alpha
        :predefine="predefineColors"
      />
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button @click="resizeForm">{{ $t("重置") }}</el-button>
      <el-button @click="cancel">{{ $t("取消") }}</el-button>
      <el-button type="primary" @click="submitForm">{{ $t("确定") }}</el-button>
    </div>
  </div>
</template>

<script>
// import Vue from 'vue'
import { getByBaseId } from '@/api/system/search/searchSqlField'
import { allListSearchSqlBase } from '@/api/system/search/searchSqlBase'
import { getInfoById, viewSave } from '@/api/system/search/searchMainView'
import searchMain from './searchMain.vue'
import conditions from './conditions'
export default {
  components: {
    searchMain,
    conditions
  },
  props: {
    module: {
      type: String,
      default: () => ''
    },
    viewId: {
      type: String,
      default: () => ''
    }
  },
  data() {
    return {
        num: 0,
      sort: 0,
        loading: false,
        // 表单参数
        form: {
            sqlBaseId: this.module,
            color: '',
            name: '',
            searchDefaultShowList: [],
            searchMainGroupList: [{
              // 组关系
              relation: 'and',
              relationList: [{ value: 'and', label: this.$t('且') }, { value: 'or', label: this.$t('或') }],
              // ---
              searchMainConditionsList: [
                {
                  fieldId: '', // id
                  conditions: '', // 条件
                  type: '',
                  fieldValue: '', // value
                  // 字典list
                  chooseList: []
                  }
              ]
            }]

        },
        // 表单校验
        rules: {
          name: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
        },
        active: false,
        disabledButton: false,
        background: '',
        // list
        dealdetailsList: [],
        // 组内关系
        rList: [{ value: 'and', label: this.$t('且') }, { value: 'or', label: this.$t('或') }],
        fieldslist: [
          {
            type: ''
          }
        ],
        dictList: [],
        predefineColors: [
          '#ff4500',
          '#ff8c00',
          '#ffd700',
          '#90ee90',
          '#32B4FF',
          '#5893FF',
          '#FDB235',
          '#FE7A85',
          '#8F8AF1'
        ]
    }
  },
  created() {
    this.load()
  },
  methods: {
    load() {
      this.loading = true
      allListSearchSqlBase().then(base => {
        base.data.forEach(baseItem => {
          if (baseItem.code === this.module) {
            getByBaseId(baseItem.id).then(response => {
               // 所有下拉字段
               this.dealdetailsList = response.data
               this.form.searchMainGroupList && this.form.searchMainGroupList.forEach(item => {
                 // 组关系
                 this.$set(item, 'relationList', this.rList)
                   item.relationList && item.relationList.forEach(rel => {
                     if (item.relation === rel.value) {
                       this.$set(item, 'relation', rel.value)
                     }
                   })
                 item.searchMainConditionsList && item.searchMainConditionsList.forEach(list => {
                   response.data.forEach(detail => {
                     if (list.fieldId === detail.name) {
                       this.$set(list, 'fieldId', detail.name)
                       this.$set(list, 'type', detail.type)
                       this.getDicts(detail.format).then(response => {
                         this.$set(list, 'chooseList', response.data)
                       })
                     } else if (list.fieldId === detail.id) {
                       this.$set(list, 'fieldId', detail.name)
                       this.$set(list, 'type', detail.type)
                       this.getDicts(detail.format).then(response => {
                         this.$set(list, 'chooseList', response.data)
                       })
                     }
                   })
                 })
               })
             this.loading = false
           })
          }
        })
      })
    },
    // 添加筛选条件
    addFiltrate() {
      const row = {
        // 组号
        sort: this.sort,
        // 组关系
        relation: 'and',
        relationList: this.rList,
        searchMainConditionsList: [
            {
              type: ''
            }
          ]
      }
      if (!(this.form.searchMainGroupList instanceof Array)) {
        this.$set(this.form, 'searchMainGroupList', [])
      }
      this.form.searchMainGroupList.push(row)
      this.sort++
    },
    // 重置表单
    resizeForm() {
      this.sort = 0
      this.form = {
          name: '',
          color: '',
          sort: '',
          sqlBaseId: this.module,
          searchDefaultShowList: [],
          searchMainGroupList: [
            {
              relation: 'and',
              relationList: this.rList,
              searchMainConditionsList: [
                {
                    fieldId: '', // id
                    conditions: '', // 条件
                    type: '',
                    fieldValue: '', // value
                    // 字典list
                    chooseList: []
                  }
              ]
            }
          ]
      }
    },
    // 组内添加
    addRange(it, index) {
      const row = {
        fieldId: '', // name
        conditions: '', // 条件
        type: '',
        fieldValue: '',
        // 字典list
        chooseList: []
      }
      this.form.searchMainGroupList[index].searchMainConditionsList.push(row)
    },
    // 获取type
    detailsChange(index, ind, val) {
      const item = this.dealdetailsList.filter(item => item.name === val)
      // 获取字典
      if (item[0].format != null || item[0].format !== '') {
        this.getDicts(item[0].format).then(format => {
          if (format.data) {
            this.form.searchMainGroupList[index].searchMainConditionsList[ind].chooseList = format.data
          }
        })
      }
      this.form.searchMainGroupList[index].searchMainConditionsList[ind].type = item[0].type
      this.form.searchMainGroupList[index].searchMainConditionsList[ind].fieldValue = ''
    },
    // 删除组内条件
    delRange(it, index) {
      if (it.searchMainConditionsList.length > 1) {
        it.searchMainConditionsList.splice(index, 1)
      } else {
        this.form.searchMainGroupList.splice(index, 1)
      }
    },

    // 删除筛选条件
    delFiltrate(index) {
        this.form.searchMainGroupList.splice(index, 1)
      this.sort--
    },

    // 初始化数据
    init(data) {
        this.$refs.form.clearValidate()
        if (data != null && data.id != null && data.id !== '') {
          getInfoById(data.id).then(response => {
            this.form = response.data
          })
        } else {
          this.resizeForm()
        }
    },
    // 取消按钮
    cancel() {
      this.resizeForm()
      this.$parent.$parent.newView = false
      this.$parent.$parent.formOpen = false
    },
    close() {
      window.localStorage.removeItem('activeIdDeal')
      window.localStorage.removeItem('activeIdFund')
      if (this.$parent.$parent.newView !== undefined) {
         this.$parent.$parent.newView = false
      }
      if (this.$parent.$parent.getViewList !== undefined) {
         this.$parent.$parent.getViewList()
      }
      if (this.$parent.$parent.getList !== undefined) {
         this.$parent.$parent.getList()
      }
      if (this.$parent.$parent.formOpen !== undefined) {
         this.$parent.$parent.formOpen = false
      }
      if (this.$parent.$parent.$parent.$parent.getViewList !== undefined) {
         this.$parent.$parent.$parent.$parent.getViewList(this.form.id)
      }
      if (this.$parent.$parent.$parent.$children[0].getList !== undefined) {
         this.$parent.$parent.$parent.$children[0].getList()
      }
      if (this.$parent.$parent.$parent.$parent.oddView !== undefined) {
         this.$parent.$parent.$parent.$parent.oddView = false
      }
    },
    /** 提交按钮 */
    submitForm: function() {
        this.$refs['form'].validate(valid => {
            if (valid) {
                this.loading = true
                this.form.dataId = this.viewId
                viewSave(this.form).then(response => {
                    if (response.code === 200) {
                        this.msgSuccess(this.$t('保存成功'))
                        if (this.$parent.title === '新建视图') { // 新建视图
                          this.close()
                        } else {
                          this.close()
                        }
                        this.$refs.form.clearValidate()
                        this.loading = false
                    } else {
                        this.msgError(response.msg)
                    }
                })
            } else {
              this.locationError(document)
            }
        })
    }

  }

}
</script>
<style scoped>
.inlineForm{
  width:150px;
  display: inline-block;
  margin-right: 15px;
}
.inlineUser{
  width:150px;display: inline-block;vertical-align: bottom;margin-right: 15px;
}
.smallC{
  padding: 3px;
}
	.colorChoose li.active {
		position: relative;
	}

	.colorChoose li.active:after {
		position: absolute;
		content: '';
		display: block;
		top: 15px;
		right: 18px;
		width: 6px;
		height: 11px;
		border-style: solid;
		border-color: white;
		border-width: 0 2px 2px 0;
		-webkit-transform: rotateZ(45deg);
		transform: rotateZ(45deg);
	}

	.colorChoose li {
		float: left;
		cursor: pointer;

	}
  .rangeItem>div{
    margin-bottom: 10px;
  }
  .rangeItem>div:last-child{
    margin-bottom: 0px;
  }

	.colorChoose li span {
		height: 24px;
		width: 24px;
		display: block;
		margin: 10px;
	}

	.el-form .el-form-item .el-form-item__label {
		display: block;
		width: 100%;
		text-align: left;
		font-size: 12px;
		line-height: 24px;
		color: #525975;
		-webkit-user-select: text;
		-moz-user-select: text;
		-ms-user-select: text;
		user-select: text;
	}
</style>
